package com.ms.controller.user;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ms.constant.MessageConstant;
import com.ms.domain.dto.AlbumCreateDTO;
import com.ms.domain.dto.AlbumUpdateDTO;
import com.ms.domain.entity.Album;
import com.ms.domain.entity.Music;
import com.ms.exception.PermissionDeniedException;
import com.ms.result.Result;
import com.ms.service.AlbumService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/api/album")
@RequiredArgsConstructor
@Tag(name = "C端专辑相关接口")
@Slf4j
public class AlbumController {
    private final AlbumService albumService;

    /**
     * 创建专辑
     *
     * @param dto 专辑创建数据
     * @return 创建的专辑
     */
    @PostMapping
    @Operation(summary = "创建专辑")
    public Result<Album> createAlbum(
            @RequestParam String title,
            @RequestParam(required = false) String description,
            MultipartFile coverImage) {
        // 验证参数
        if (coverImage == null) {
            return Result.badRequest("请上传专辑封面");
        }
        AlbumCreateDTO dto = AlbumCreateDTO.builder()
                .title(title)
                .description(description)
                .build();
        return Result.success(albumService.createAlbum(dto, coverImage));
    }

    /**
     * 更新专辑
     *
     * @param dto 专辑更新数据
     */
    @PutMapping
    @Operation(summary = "更新专辑")
    public Result<Void> updateAlbum(@RequestBody @Valid AlbumUpdateDTO dto) {
        try {
            albumService.updateAlbum(dto);
            return Result.success();
        } catch (PermissionDeniedException e) {
            return Result.forbidden(e.getMessage());
        }
    }

    /**
     * 删除专辑
     *
     * @param id 专辑 id
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "根据 id 删除专辑")
    public Result<Void> deleteAlbum(@PathVariable Integer id) {
        try {
            albumService.deleteAlbum(id);
            return Result.success();
        } catch (PermissionDeniedException e) {
            return Result.forbidden(e.getMessage());
        }
    }

    /**
     * 获取专辑
     *
     * @param id 专辑ID
     * @return 专辑详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "通过 id 获取专辑")
    public Result<Album> getAlbumById(@PathVariable Integer id) {
        try {
            return Result.success(albumService.getAlbumById(id));
        } catch (Exception e) {
            return Result.notFound(e.getMessage());
        }
    }

    /**
     * 获取专辑列表
     *
     * @param page 页码
     * @param size 每页数量
     * @return 专辑列表
     */
    @GetMapping
    @Operation(summary = "分页获取专辑列表")
    public Result<Page<Album>> getAlbumPage(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        return Result.success(albumService.getAlbumPage(page, size));
    }

    /**
     * 获取专辑包含的音乐
     *
     * @param albumId 专辑ID
     * @return 专辑包含的音乐列表
     */
    @GetMapping("/{albumId}/musics")
    @Operation(summary = "根据专辑 id 查询包含音乐")
    public Result<List<Music>> getMusicByAlbumId(@PathVariable Integer albumId) {
        log.info("获取专辑 {} 中的音乐", albumId);
        try {
            return Result.success(albumService.getMusicByAlbumId(albumId));
        } catch (Exception e) {
            return Result.notFound(e.getMessage());
        }
    }

    /**
     * 分页获取专辑包含的音乐
     *
     * @param albumId 专辑ID
     * @param page    页码
     * @param size    每页数量
     * @return 专辑包含的音乐分页数据
     */
    @GetMapping("/{albumId}/musics/page")
    @Operation(summary = "分页获取专辑包含的音乐")
    public Result<Page<Music>> getMusicPageByAlbumId(
            @PathVariable Integer albumId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        log.info("分页获取专辑 {} 中的音乐，页码：{}，大小：{}", albumId, page, size);
        try {
            return Result.success(albumService.getMusicPageByAlbumId(albumId, page, size));
        } catch (Exception e) {
            return Result.notFound(e.getMessage());
        }
    }

    /**
     * 添加音乐到专辑
     *
     * @param albumId 专辑ID
     * @param musicId 音乐ID
     */
    @PostMapping("/{albumId}/add-music/{musicId}")
    @Operation(summary = "添加音乐到专辑")
    public Result<Void> addMusicToAlbum(
            @PathVariable Integer albumId,
            @PathVariable Integer musicId) {
        try {
            albumService.addMusicToAlbum(albumId, musicId);
            return Result.success();
        } catch (PermissionDeniedException e) {
            return Result.forbidden(e.getMessage());
        } catch (Exception e) {
            return Result.notFound(e.getMessage());
        }
    }

    /**
     * 从专辑中移除音乐
     *
     * @param albumId 专辑ID
     * @param musicId 音乐ID
     */
    @DeleteMapping("/{albumId}/remove-music/{musicId}")
    @Operation(summary = "从专辑中移除音乐")
    public Result<Void> removeMusicFromAlbum(
            @PathVariable Integer albumId,
            @PathVariable Integer musicId) {
        try {
            albumService.removeMusicFromAlbum(albumId, musicId);
            return Result.success();
        } catch (PermissionDeniedException e) {
            return Result.forbidden(e.getMessage());
        }
    }

    /**
     * 获取用户专辑列表
     *
     * @param userId 用户ID
     * @return 用户专辑列表
     */
    @GetMapping("/user/{userId}")
    @Operation(summary = "通过 用户id 获取用户专辑列表")
    public Result<List<Album>> getUserAlbums(@PathVariable Integer userId) {
        try {
            return Result.success(albumService.getUserAlbums(userId));
        } catch (PermissionDeniedException e) {
            return Result.forbidden(e.getMessage());
        }
    }

    /**
     * 分页获取用户专辑列表
     *
     * @param userId 用户ID
     * @param page   页码
     * @param size   每页数量
     * @return 用户专辑分页数据
     */
    @GetMapping("/user/{userId}/page")
    @Operation(summary = "分页获取用户专辑列表")
    public Result<Page<Album>> getUserAlbumsPage(
            @PathVariable Integer userId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            return Result.success(albumService.getUserAlbumsPage(userId, page, size));
        } catch (PermissionDeniedException e) {
            return Result.forbidden(e.getMessage());
        }
    }
}